package service

import (
	"crypto/x509"
	"encoding/pem"
	"errors"
	"gin-luban-server/global"
	"gin-luban-server/model"
	"gin-luban-server/model/request"
)

//@author: [piexlmax](https://github.com/piexlmax)
//@function: CreateNginxDomainCert
//@description: 创建NginxDomainCert记录
//@param: Cert model.NginxDomainCert
//@return: err error
func CreateNginxDomainCertByFile(Cert model.NginxDomainCert) (err error) {
    if Cert.Pem == ""{
        err = errors.New("Pem  Null")
    	return
	}

	// 解析证书
    err, Cert.Issued, Cert.Dns, Cert.Validity, Cert.Deadline = parsePemFile([]byte(Cert.Pem))
    if err != nil{
    	return err
	}

	// 证书保存到数据库中
	err = global.GVA_DB.Create(&Cert).Error
	return err
}

// 解析证书信息
func parsePemFile(certPEMBlock []byte) (err error, Origan, Dns, Before, After string) {
	certDERBlock, _ := pem.Decode(certPEMBlock)
	if certDERBlock == nil {
		err = errors.New("Parse Failed")
		return
	}
	x509Cert, err := x509.ParseCertificate(certDERBlock.Bytes)
	if err != nil {
		return
	}

	if len(x509Cert.Subject.Organization) > 0 {
		Origan = x509Cert.Subject.Organization[0]
	}

	if len(x509Cert.DNSNames) > 0 {
		Dns = x509Cert.DNSNames[0]
	}

	Before, After = x509Cert.NotBefore.Format("2006-01-02 15:04"), x509Cert.NotAfter.Format("2006-01-02 15:04")
    return
}



// 删除操作
func DeleteNginxDomainCert(id float64) (err error) {
	var Cert model.NginxDomainCert
	// 删除
	err = global.GVA_DB.Where("id = ?", id).Delete(&Cert).Error
	return err
}


func GetNginxDomainCertById(id float64) (err error, Cert model.NginxDomainCert) {
	err = global.GVA_DB.Where("id = ?", id).First(&Cert).Error
	return err, Cert
}



// 查 list
func GetNginxDomainCertInfoList(info request.NginxDomainCertSearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&model.NginxDomainCert{})
	var Certs []model.NginxDomainCert
	// 如果有条件搜索 下方会自动创建搜索语句
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&Certs).Error
	return err, Certs, total
}